package luj.tool.jnproxyan.proxy.stats.connect;

import luj.data.api.Data;
import luj.data.api.use.UseGroup;
import luj.tool.jnproxyan.proxy.database.DatabaseState;
import luj.tool.jnproxyan.proxy.util.data.session.DataUsingStarter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.Instant;
import java.util.Map;

@Component
public class ConnectFailAdder {

  public ConnectFailAdder inject(ConnectStats stats, String host, int port, DataUsingStarter.Session session) {
    ConnectFailAdder result = new ConnectFailAdder();
    result._stats = stats;
    result._host = host;
    result._port = port;

    result._dbState = session.db();
    result._loadCache = session.loaded();
    result._using = session.using();

    result._itemGetter = _itemGetter;
    return result;
  }

  public void add() {
    ConnectStats.Item item = _itemGetter.inject(_stats, _host, _dbState, _loadCache, _using).getOrInit();
    item.requestTotal().add(1);
    item.failCount().add(1);

    long now = Instant.now().toEpochMilli();
    item.lastFailTime().set(now);
  }

  ConnectStats _stats;
  String _host;
  int _port;

  DatabaseState _dbState;
  Map<String, Data> _loadCache;
  UseGroup _using;

  @Autowired
  StatsItemGetter _itemGetter;
}
